package com.qf.shiro;

import com.qf.pojo.DtsAdmin;
import com.qf.service.DtsAdminService;
import com.qf.service.DtsPermissionService;
import com.qf.service.DtsRoleService;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @author 千锋教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
public class AdminAuthorizingRealm extends AuthorizingRealm {

    @Autowired
    DtsAdminService adminService;

    @Autowired
    DtsRoleService roleService;

    @Autowired
    DtsPermissionService permissionService;

    //提供授权信息
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取 认证成功后 存储到session的对象
        DtsAdmin admin = (DtsAdmin) principals.getPrimaryPrincipal();
        //获取 该admin对应的角色id
        Integer[] roleIds = admin.getRoleIds();

        //根据角色id获取 角色信息
        Set<String> roles = roleService.findRoleByIds(roleIds);

        //根据角色id获取权限信息
        Set<String> perms = permissionService.findPermByIds(roleIds);


        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roles);
        authorizationInfo.setStringPermissions(perms);

        return authorizationInfo;
    }

    /**
     * 1. 获取用户输入的账号和 密码信息
     * 2. 获取数据库中的该用户信息
     * 3. 校验
     * @param token
     * @return
     * @throws
     */
    //提供认证信息(认证)
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户输入的账号和 密码信息
        //获取用户名
        String username = (String) token.getPrincipal();
        //获取密码
        String password = new String((char[])token.getCredentials());

        //获取数据库中的该用户信息(根据用户名获取用户数据)
        DtsAdmin admin = adminService.findByUsername(username);

        //校验
        if(admin == null){
            throw new UnknownAccountException("未知的账户");
        }

        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

        if(admin.getPassword() == null || ! passwordEncoder.matches(password, admin.getPassword()) ) {
            throw new CredentialsException("密码错误");
        }
        //如果 deleted为 1， 则被逻辑删除
        if(admin.getDeleted()) {
            throw new LockedAccountException("账户被锁定");
        }

        //参数1: 用户对象， 参数2： 密码  参数3： 真实姓名
        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(admin  ,password, admin.getUsername());
        return authenticationInfo;
    }
}
